<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head th:fragment="head">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Smart PlantUML</title>
    <link rel="stylesheet" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/webjars/codemirror/lib/codemirror.css}"/>
    <link rel="stylesheet" th:href="@{/webjars/codemirror/theme/darcula.css}"/>
    <link rel="stylesheet" th:href="@{/webjars/codemirror/theme/solarized.css}"/>
    <style>
        #form-group-source {
            min-height: 500px;
        }
        .CodeMirror {
            border: 1px solid #eee;
            height: 100%;
        }
        .view-container {
            width: 48%;
            float: left;
            margin-left: 3%;
            border: 1px solid #e3e2e2;
            overflow: auto; /* 当内容超出容器尺寸时显示滚动条 */
            overflow-x: auto;
        }
        #form-group-source {
            width: 48%;
            float: left;
            height: 500px;
            overflow: auto; /* 当内容超出容器尺寸时显示滚动条 */
        }
         #source {
            height: 300px; /* 设置您想要的固定高度 */
            resize: vertical; /* 允许用户垂直调整大小（可选） */
            overflow-y: auto; /* 当内容超出高度时显示垂直滚动条 */
            overflow-x: auto; /* 当内容超出宽度时显示水平滚动条（如果需要） */
            box-sizing: border-box; /* 确保 padding 和 border 包含在 height 内 */
            font-family: inherit; /* 保持字体一致 */
            font-size: 10px;
            padding: 10px;
        }
        #container {
            display: flex;
            flex: 1;
            height: 300px;
            width: 100%;
            overflow: hidden;
        }
    </style>
    <script th:src="@{/webjars/codemirror/lib/codemirror.js}"></script>
</head>
<body>
<a th:href="${currentUrl}">Current Page</a>
<a th:href="${baseUrl}">Base URL</a>
<div>
    <!--<header th:fragment="header" class="text-center">
        <h1>Smart PlantUML</h1>

        &lt;!&ndash;<p class="lead">Create your <a href="http://plantuml.com">PlantUML</a> diagrams directly in your browser !</p>&ndash;&gt;
    </header>-->

    <!-- 在 header 部分添加类型选择下拉框 -->
    <header th:fragment="header" class="text-left">
        <h1>Smart PlantUML</h1>
        <div class="container-fluid mt-3">
            <div class="row">
                <div class="col-md-3">
                    <div class="input-group input-group-sm">
                        <label class="input-group-text" for="plantUmlType">Diagram Type</label>
                        <select id="plantUmlType" class="form-select" onchange="changeType(this.value)">
                            <option th:each="plantType : ${plantUmlTypes}"
                                    th:value="${plantType.key}"
                                    th:text="${plantType.val}"
                                    th:selected="${plantType.key == currentType}"></option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </header>



    <div class="container" th:fragment="content">

        <form id="workspace" th:fragment="workspace (source, encodedSource)" class="form" method="post"
              accept-charset="UTF-8" th:action="@{/uml}">
            <div id="form-group-source" class="form-group"
                 style="width: 48%;float: left;height: 500px;font-size: 13px;">
                <textarea id="source" class="form-control" rows="20" name="source" th:text="${source}"></textarea>
            </div>
            <div class="view-container"
                 style="width: 48%;float: left;height: 500px;
                 margin-left: 3%;border: 1px solid #e3e2e2;"
                 th:fragment="render (encodedSource)">
                <div class="col-md-6" style="width: 100%;">
                    <div class="form-group">
                        <img th:src="@{/png/{encodedSource}(encodedSource=${encodedSource})}" alt="PlantUML diagram"
                             style="margin: 1%;"/>
                    </div>
                </div>
            </div>


            <div class="form-row">
                <div class="form-group">
                    <div class="input-group input-group-sm">
                        <div class="input-group-prepend">
                            <label class="input-group-text" for="theme">Theme</label>
                        </div>
                        <select id="theme" class="custom-select" onchange="Editor.changeTheme()">
                            <option selected>solarized dark</option>
                            <option>solarized light</option>
                            <option>default</option>
                            <option>darcula</option>

                        </select>
                    </div>
                    <div class="col">

                        <a class="btn btn-sm btn-outline-primary" target="_blank"
                           th:href="@{/pdf/{encodedSource}(encodedSource=${encodedSource})}">View as PDF</a>
                        <a class="btn btn-sm btn-outline-primary" target="_blank"
                           th:href="@{/png/{encodedSource}(encodedSource=${encodedSource})}">View as PNG</a>
                        <a class="btn btn-sm btn-outline-primary" target="_blank"
                           th:href="@{/svg/{encodedSource}(encodedSource=${encodedSource})}">View as SVG</a>
                        <a class="btn btn-sm btn-outline-primary" target="_blank"
                           th:href="@{/txt/{encodedSource}(encodedSource=${encodedSource})}">View as ASCII Art</a>
                        <a class="btn btn-sm btn-outline-primary" target="_blank"
                           th:href="@{/vdx/{encodedSource}(encodedSource=${encodedSource})}">Download as VDX</a>
                        <a class="btn btn-sm btn-outline-primary" target="_blank"
                           th:href="@{/base64/{encodedSource}(encodedSource=${encodedSource})}">View as base64</a>
                        <input type="submit" class="btn btn-sm btn-primary"/>
                    </div>
                </div>

            </div>
        </form>
    </div>


    <form th:fragment="url (encodedSource)" class="form" method="post" accept-charset="UTF-8"
          th:action="@{/uml/recover}">
        <div class="form-group">
            <label class="mb-sm-0" for="url"><small>You can enter here a previously generated URL:</small></label>
            <div class="input-group input-group-sm">
                <!--<input id="url" class="form-control text-monospace" name="url" type="text" size="150"
                       th:value="${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder).fromContextPath(#request).path('/png/{source}').build(encodedSource)}"/>-->
                <input id="url" class="form-control text-monospace" name="url" type="text" size="150"
                       th:value="${generatedUrl}"/>
                <div class="input-group-append">
                    <button type="submit" class="btn btn-primary">Recover</button>
                    <button type="button" class="btn btn-success" onclick="Editor.copyUrl()">Copy</button>
                </div>
            </div>
        </div>
    </form>

    <footer class="text-muted text-center" th:fragment="footer">
        <small th:text="${T(net.sourceforge.plantuml.version.Version).fullDescription()}"></small>
    </footer>
</div>

<script th:fragment="script">

    function changeType(type) {
        // 获取当前URL
        const url = new URL(window.location);
        // 设置type参数
        url.searchParams.set('type', type);
        // 刷新页面
        window.location.href = url.toString();
    }

let Editor = (function () {
    "use strict";

    let codeMirror = CodeMirror.fromTextArea(document.getElementById('source'), {
        lineNumbers: true,
        styleActiveLine: true,
        viewportMargin: Infinity
    });

    let debounceTimer;
    let imageView = document.querySelector(".view-container img");

    // 恢复主题
    let savedTheme = localStorage.getItem('theme') || 'solarized dark';
    codeMirror.setOption('theme', savedTheme);
    document.getElementById('theme').value = savedTheme;

    // 工具函数：判断变更是否“有意义”
    function isSignificantChange(change) {
        const text = change.text.join('');
        const removed = change.removed ? change.removed.join('') : '';

        // 仅空白或换行，不算重要变更
        if (/^[\s\n\r]*$/.test(text) && /^[\s\n\r]*$/.test(removed)) {
            return false;
        }
        return /[^\s\n\r]/.test(text) || /[^\s\n\r]/.test(removed);
    }

    // 函数：发送 AJAX 请求并更新图片
    function updatePreview() {
const source = codeMirror.getValue();
const formData = new URLSearchParams();
formData.append('source', source);

    fetch('/uml/async', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formData
    })
    .then(response => {
        if (!response.ok) throw new Error('Network error');
        return response.json();
    })
    .then(data => {
        if (data.encodedSource) {
            const enc = data.encodedSource;
            const pngUrl = `/png/${enc}`;
            const svgUrl = `/svg/${enc}`;
            const txtUrl = `/txt/${enc}`;
            const fullUrl = `${window.location.protocol}//${window.location.host}/png/${enc}`; // 完整 URL

            // 更新图片（带防缓存）
            imageView.src = pngUrl + '?t=' + Date.now();

            // 更新三个下载按钮
            document.querySelector('a[href*="/png/"]').href = pngUrl;
            document.querySelector('a[href*="/svg/"]').href = svgUrl;
            document.querySelector('a[href*="/txt/"]').href = txtUrl;

            // 更新 URL 输入框
            const urlInput = document.getElementById('url');
            if (urlInput) {
                urlInput.value = fullUrl;
            }

            console.log("Preview updated:", enc);
        } else if (data.error) {
            console.error("Render error:", data.error);
            imageView.alt = "Render Error";
        }
    })
    .catch(err => {
        console.error("Fetch failed:", err);
        imageView.alt = "Connection Error";
    });
}

    // 监听 change 事件
    codeMirror.on("change", function (cm, change) {
        if (isSignificantChange(change)) {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                updatePreview(); // 500ms 后异步更新
            }, 500); // ✅ 500ms 防抖
        }
    });

    // 初始化：如果已有图，先加载一次
    if (imageView && imageView.src) {
        // 可选：首次加载时也走 AJAX
    }

    return {
        changeTheme: function () {
            let input = document.getElementById('theme');
            let theme = input.options[input.selectedIndex].textContent;
            codeMirror.setOption('theme', theme);
            localStorage.setItem('theme', theme);
        },
        copyUrl: function () {
            let url = document.getElementById('url');
            url.select();
            document.execCommand("copy");
            alert("URL copied!");
        }
    };
})();
</script>
</body>
</html>
